<?php

class products extends cms_controller {

    var $first = true;

    function __construct() {
        parent::__construct();
        $this->load->model('products_model', 'product');
    }

    function index() {
        $this->load->model('categories_model', 'cats');
        $this->load->model('trades_model', 'trades');
        $this->pass['maincats'] = $this->cats->get(array('parent' => '0'));
        $this->pass['trades'] = $this->trades->get();
        $this->themes->render(__CLASS__ . '/index', $this->pass);
    }

    function category($id = false) {
        if ($id) {
            $this->load->model('categories_model', 'cats');
            $cat = $this->cats->is_found(array('id' => $id), array(), 'row', '');
            $this->pass['cat'] = $cat;
            if ($cat->parent == '0') {
                $subcats = $this->cats->get(array('parent' => $id));
                $this->pass['cats'] = $subcats;
                $this->themes->render('products/category', $this->pass);
            } else {
                $products = $this->product->get(array('subcat_id' => $id));
                $this->pass['products'] = $products;
                $this->themes->render('products/subcategory', $this->pass);
            }
        } else {
            show_404();
        }
    }

    function advanced() {
        if ($this->input->post()) {
            $where = array();
            $or_like = array();
            $additional = array();
            $keyword = array();
            $this->load->library('form_validation');

            $this->form_validation->set_rules('maincat', lang('label_main_cat'), 'is_natural');
            $this->form_validation->set_rules('subcat', lang('label_sub_cat'), 'is_natural');
            $this->form_validation->set_rules('trademark', lang('label_menu_link_trade'), 'is_natural');
            $this->form_validation->set_rules('condition', lang('label_prod_condition'), 'callback_checkcond');
            $this->form_validation->set_rules('storename', lang('label_store') . ' ' . lang('label_name'), 'alpha');
            $this->form_validation->set_rules('pricefrom', lang('label_product_price') . ' ' . lang('label_from'), 'numeric');
            $this->form_validation->set_rules('priceto', lang('label_product_price') . ' ' . lang('label_to'), 'numeric');
            if ($this->form_validation->run()) {
                if ($this->input->post('keyword')) {
                    $keyword['name'] = $this->input->post('keyword');
                    $keyword['descrebtion'] = $this->input->post('keyword');
                    $keyword['details'] = $this->input->post('keyword');
                }

                if ($this->input->post('subcat')) {
                    $where['subcat_id'] = $this->input->post('subcat');
                } elseif ($this->input->post('maincat')) {
                    $ids = get_sub_cats_ids($this->input->post('maincat'));
                    if (count($ids) > 0)
                        $where['subcat_id'] = $ids;
                }

                if ($this->input->post('trademark')) {
                    $where['trade_id'] = $this->input->post('trademark');
                }

                if ($this->input->post('condition') && $this->input->post('condition') != 'all') {
                    $where['condition'] = strtoupper($this->input->post('condition'));
                }

                if ($this->input->post('storename')) {
                    $ids = get_store_id_from_name($this->input->post('storename'));
                    if (count($ids) > 0) {
                        $where['store_id'] = $ids;
                    }
                }

                if ($this->input->post('size')) {
                    foreach ($this->input->post('size') as $k => $v) {
                        $or_like['size'][] = $v;
                    }
                }

                if ($this->input->post('color')) {
                    foreach ($this->input->post('color') as $k => $v) {
                        $or_like['colors'][] = $v;
                    }
                }

                if ($this->input->post('pricefrom')) {
                    $where['price >='] = $this->input->post('pricefrom');
                }

                if ($this->input->post('priceto')) {
                    $where['price <='] = $this->input->post('priceto');
                }

                if ($this->input->post('sproducts')) {
                    $where['special_product'] = 'YES';
                }

                if ($this->input->post('offers')) {
                    $where['discount_precentage >'] = '0';
                }
                
                if ($this->input->post('additional')) {
                    $additional = $this->input->post('additional');
                }

                $this->pass['products'] = $this->product->get_advanced($where, $or_like, $additional, $keyword);
                //die($this->db->last_query());
                $this->themes->render('products/advanced', $this->pass);
            } else {
                get_validation_errors();
            }
        }
        else
            redirect(__CLASS__);
    }

    function stores($id = FALSE) {
        if (is_numeric($id)) {
            $this->load->model('store_model', 'stores');
            $this->pass['store'] = $store = $this->stores->is_found(array('id' => $id), array(), 'row', $this->agent->referrer());
            $this->pass['products'] = $products = $this->product->get(array('store_id' => $id));
            $this->themes->render('products/stores', $this->pass);
        } else {
            show_404();
        }
    }
    
    function brands($id = FALSE) {
        if (is_numeric($id)) {
            $this->load->model('trades_model', 'trades');
            $this->pass['trade'] = $trade = $this->trades->is_found(array('id' => $id), array(), 'row', $this->agent->referrer());
            $this->pass['products'] = $products = $this->product->get(array('trade_id' => $id));
            $this->themes->render('products/brands', $this->pass);
        } else {
            show_404();
        }
    }

    private function upload_file($input) {

        $config['upload_path'] = PRODUCT_PATH . '/temp/';
        $config['file_name'] = md5(time() . $this->session->userdata('user_NAME') . $input);
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['max_size'] = '1024';
        $config['max_width'] = '1024';
        $config['max_height'] = '768';
        if ($this->first) {
            $this->load->library('upload', $config);
            $this->first = false;
        } else {
            $this->upload->initialize($config);
        }

        if (!$this->upload->do_upload($input)) {
            return $this->upload->display_errors();
        } else {
            $filedata = $this->upload->data();
            $this->session->set_userdata($input, $filedata['file_name']);
            return true;
        }
    }

    function add() {
        $this->load->model('store_model', 'stores');
        $store = $this->stores->is_found(array('owner_id' => $this->user_id), array(), 'row', __CLASS__ . '/create/1', 'message_create_yourstore');
        if ($store->active == 'NO') {
            $this->themes->set_message(array('url' => 'store', 'type' => 'error', 'message' => 'message_store_not_active_product'));
        }
        $values = unserialize($store->package_values);
        if ($values['prodnum'] != 'unlimit') {
            $prods = $this->product->get(array('store_id' => $store->id));
            if (count($prods) >= $values['prodnum']) {
                $this->themes->set_message(array('url' => 'store', 'type' => 'error', 'message' => 'message_store_max_products'));
            }
        }
        $this->load->model('categories_model', 'cats');
        $this->load->model('trades_model', 'trades');
        $this->pass['maincats'] = $mcats = $this->cats->get(array('parent' => '0'));

        if ($this->input->post()) {
            $this->session->set_userdata('post', $this->input->post());
            $this->load->library('form_validation');

            $this->form_validation->set_rules('maincat', lang('label_main_cat'), 'trim|required|is_natural|is_found[categories.id]');
            $this->form_validation->set_rules('subcat', lang('label_sub_cat'), 'trim|required|is_natural|is_found[categories.id]');
            $this->form_validation->set_rules('trademark', lang('label_menu_link_trade'), 'trim|required|is_natural|is_found[trades.id]');
            $this->form_validation->set_rules('prodname', lang('label_product_name'), 'trim|required|min_length[5]');
            $this->form_validation->set_rules('condition', lang('label_prod_condition'), 'trim|required|callback_checkcond');
            $this->form_validation->set_rules('shipingon', lang('label_prod_condition'), 'trim|required|callback_checkshipingon');
            $this->form_validation->set_rules('price', lang('label_product_price'), 'trim|required|numeric');
            $this->form_validation->set_rules('discount_prec', lang('label_product_disc_prec'), 'trim|numeric');
            $this->form_validation->set_rules('discount_price', lang('label_product_disc_price'), 'trim|numeric');
            $this->form_validation->set_rules('quentity', lang('label_product_quentity'), 'trim|required|is_natural_no_zero');
            $this->form_validation->set_rules('shipingweghit', lang('label_product_shiping_weghit'), 'trim|required|numeric');
            $this->form_validation->set_rules('shipingunsupport', lang('label_product_shiping_unsupport'), 'trim|required|numeric');
            if ($this->input->post('special_product')) {
                $this->form_validation->set_rules('special_days', lang('label_product_special_days'), 'trim|required|is_natural_no_zero');
            }
            if ($this->input->post('returnspolicy')) {
                $this->form_validation->set_rules('returnsdays', lang('label_returns_days'), 'trim|is_natural_no_zero|required');
            }

            if ($this->form_validation->run()) {
                for ($i = 1; $i <= $values['prodimg']; $i++) {
                    $upload = NULL;
                    $upload = $this->upload_file("image$i");
                }
                $images = array();
                for ($i = 1; $i <= $values['prodimg']; $i++) {
                    if (@copy(PRODUCT_PATH . "/temp/" . $this->session->userdata("image$i"), PRODUCT_PATH . "/" . $this->session->userdata("image$i"))) {
                        @unlink(PRODUCT_PATH . "/temp/" . $this->session->userdata("image$i"));
                        $default = 'no';
                        if ($this->input->post('dimage') == $i)
                            $default = 'yes';
                        $images[] = array($this->session->userdata("image$i"), $default);
                        $this->session->unset_userdata("image$i");
                    }
                }
                $save['store_id'] = $store->id;
                $save['mcat_id'] = $this->input->post('maincat');
                $save['subcat_id'] = $this->input->post('subcat');
                $save['trade_id'] = $this->input->post('trademark');
                $save['condition'] = strtoupper($this->input->post('condition'));
                $save['name'] = $this->input->post('prodname');
                $save['descrebtion'] = $this->input->post('descrebtion');
                if ($values['prodvedio'] == 'true')
                    $save['vedio'] = $this->input->post('video');
                if (color_need($this->input->post('maincat'))) {
                    $save['colors'] = serialize($this->input->post('color'));
                }
                if (size_need($this->input->post('maincat'))) {
                    $save['size'] = serialize($this->input->post('size'));
                }

                $save['price'] = $this->input->post('price');
                $save['discount_precentage'] = $this->input->post('discount_prec');
                $save['discount_price'] = $this->input->post('price') - ($this->input->post('price') * $this->input->post('discount_prec') / 100);
                $save['quantity'] = $this->input->post('quentity');
                $save['shiping_weghite'] = $this->input->post('shipingweghit');
                $save['shiping_unsuport'] = $this->input->post('shipingunsupport');
                $save['shiping_on'] = strtoupper($this->input->post('shipingon'));
                $save['details'] = $this->input->post('details');
                if ($this->input->post('returnspolicy')) {
                    $save['returns_policy'] = 'YES';
                    $save['returns_days'] = $this->input->post('returnsdays');
                    $save['returns_note'] = $this->input->post('returnsnote');
                } else {
                    $save['returns_policy'] = 'NO';
                    $save['returns_days'] = '';
                    $save['returns_note'] = '';
                }
                if ($this->input->post('special_product')) {
                    $save['days'] = $this->input->post('special_days');
                    $string = md5($save['store_id'] + $save['condition'] + $save['name'] + $save['shiping_weghite'] + time());
                    $save['inv_num'] = substr($string, 0, 9);
                    $save['user_id'] = $this->user_id;
                    $save['total'] = (int) $save['days'] * (double) get_option('special_product_price');
                    $save['must_pay'] = $save['total'];
                    $save['title'] = 'message_special_product';
                    $save['for'] = 'special_product';
                }
                $save['images'] = serialize($images);
                if ($id = $this->product->save($save)) {
                    if ($this->input->post('special_product')) {
                        $this->load->model('invoicies_model');
                        $this->invoicies_model->save($save);
                    }
                    $this->load->model('categories_model', 'cats');
                    $cat = $this->cats->get(array('categories.id' => $this->input->post('subcat')), FALSE, 'row');
                    if ($cat->additional != '0') {
                        $additional = get_cat_additional($cat->id);
                        if ($additional) {
                            $addpost = $this->input->post('additional');
                            $adata['product_id'] = $id;
                            $adata['category_id'] = $this->input->post('subcat');
                            foreach ($additional as $addt) {
                                if (key_exists($addt->code, $addpost)) {
                                    if ($addt->type == 'checkbox')
                                        $adata['value'] = serialize($addpost[$addt->code]);
                                    else
                                        $adata['value'] = $addpost[$addt->code];
                                    $adata['code'] = $addt->code;
                                    save_product_additional($adata);
                                }
                            }
                        }
                    }

                    $this->session->unset_userdata('post');
                    $this->themes->set_message(array('type' => 'success', 'url' => 'store', 'message' => 'message_save_success'));
                } else {
                    get_save_error();
                }
            } else {
                get_validation_errors();
            }
        }
        $this->pass['trades'] = $this->trades->get();
        $this->pass['prodimg'] = $values['prodimg'];
        $this->pass['prodvedio'] = $values['prodvedio'];
        $this->pass['storeid'] = $store->id;
        $this->themes->render('products/add', $this->pass);
    }

    function checkshipingon($str) {
        if (!in_array($str, array('dealer', 'buyer', 'between'))) {
            $this->form_validation->set_message('checkshipingon', lang('message_checkshipingon'));
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function checkcond($str) {
        if(empty($str))
            return TRUE;
        if (!in_array($str, array('new', 'used', 'all'))) {
            $this->form_validation->set_message('checkcond', lang('message_checkcond'));
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function edit($id = false) {
        if ($id) {
            $this->load->model('store_model', 'stores');
            $product = $this->product->is_found(array('id' => $id), array(), 'row', 'store');
            $this->load->model('store_model', 'stores');
            $store = $this->stores->is_found(array('owner_id' => $this->user_id), array(), 'row', __CLASS__ . '/create/1', 'message_create_yourstore');
            if ($store->active == 'NO') {
                $this->themes->set_message(array('url' => 'store', 'type' => 'error', 'message' => 'message_store_not_active_product'));
            }
            $values = unserialize($store->package_values);
            if ($values['prodnum'] != 'unlimit') {
                $prods = $this->product->get(array('store_id' => $store->id));
                if (count($prods) >= $values['prodnum']) {
                    $this->themes->set_message(array('url' => 'store', 'type' => 'error', 'message' => 'message_store_max_products'));
                }
            }
            $this->load->model('categories_model', 'cats');
            $this->load->model('trades_model', 'trades');
            $this->pass['maincats'] = $mcats = $this->cats->get(array('parent' => '0'));

            if ($this->input->post()) {
                $this->session->set_userdata('post', $this->input->post());
                $this->load->library('form_validation');

                $this->form_validation->set_rules('maincat', lang('label_main_cat'), 'trim|required|is_natural|is_found[categories.id]');
                $this->form_validation->set_rules('subcat', lang('label_sub_cat'), 'trim|required|is_natural|is_found[categories.id]');
                $this->form_validation->set_rules('trademark', lang('label_menu_link_trade'), 'trim|required|is_natural|is_found[trades.id]');
                $this->form_validation->set_rules('prodname', lang('label_product_name'), 'trim|required|min_length[5]');
                $this->form_validation->set_rules('condition', lang('label_prod_condition'), 'trim|required|callback_checkcond');
                $this->form_validation->set_rules('shipingon', lang('label_prod_condition'), 'trim|required|callback_checkshipingon');
                $this->form_validation->set_rules('price', lang('label_product_price'), 'trim|required|numeric');
                $this->form_validation->set_rules('discount_prec', lang('label_product_disc_prec'), 'trim|numeric');
                $this->form_validation->set_rules('discount_price', lang('label_product_disc_price'), 'trim|numeric');
                $this->form_validation->set_rules('quentity', lang('label_product_quentity'), 'trim|required|is_natural_no_zero');
                $this->form_validation->set_rules('shipingweghit', lang('label_product_shiping_weghit'), 'trim|required|numeric');
                $this->form_validation->set_rules('shipingunsupport', lang('label_product_shiping_unsupport'), 'trim|required|numeric');
                if ($this->input->post('special_product')) {
                    $this->form_validation->set_rules('special_days', lang('label_product_special_days'), 'trim|required|is_natural_no_zero');
                }
                if ($this->input->post('returnspolicy')) {
                    $this->form_validation->set_rules('returnsdays', lang('label_returns_days'), 'trim|is_natural_no_zero|required');
                }

                if ($this->form_validation->run()) {
                    for ($i = 1; $i <= $values['prodimg']; $i++) {
                        $upload = NULL;
                        $upload = $this->upload_file("image$i");
                    }
                    $images = array();
                    for ($i = 1; $i <= $values['prodimg']; $i++) {
                        if ($this->input->post("doneimage$i")) {
                            $default = 'no';
                            if ($this->input->post('dimage') == $i)
                                $default = 'yes';
                            $images[] = array($this->input->post("doneimage$i"), $default);
                        } else {
                            if (@copy(PRODUCT_PATH . "/temp/" . $this->session->userdata("image$i"), PRODUCT_PATH . "/" . $this->session->userdata("image$i"))) {
                                @unlink(PRODUCT_PATH . "/temp/" . $this->session->userdata("image$i"));
                                $default = 'no';
                                if ($this->input->post('dimage') == $i)
                                    $default = 'yes';
                                $images[] = array($this->session->userdata("image$i"), $default);
                                $this->session->unset_userdata("image$i");
                            }
                        }
                        if(is_array($this->input->post('removed')))
                        foreach ($this->input->post('removed') as $k => $v) {
                            @unlink(PRODUCT_PATH . $v);
                        }
                    }
                    $save['store_id'] = $store->id;
                    $save['mcat_id'] = $this->input->post('maincat');
                    $save['subcat_id'] = $this->input->post('subcat');
                    $save['trade_id'] = $this->input->post('trademark');
                    $save['condition'] = strtoupper($this->input->post('condition'));
                    $save['name'] = $this->input->post('prodname');
                    $save['descrebtion'] = $this->input->post('descrebtion');
                    if ($values['prodvedio'] == 'true')
                        $save['vedio'] = $this->input->post('video');
                    if (color_need($this->input->post('maincat'))) {
                        $save['colors'] = serialize($this->input->post('color'));
                    }
                    if (size_need($this->input->post('maincat'))) {
                        $save['size'] = serialize($this->input->post('size'));
                    }

                    $save['price'] = $this->input->post('price');
                    $save['discount_precentage'] = $this->input->post('discount_prec');
                    $save['discount_price'] = $this->input->post('price') - ($this->input->post('price') * $this->input->post('discount_prec') / 100);
                    $save['quantity'] = $this->input->post('quentity');
                    $save['shiping_weghite'] = $this->input->post('shipingweghit');
                    $save['shiping_unsuport'] = $this->input->post('shipingunsupport');
                    $save['shiping_on'] = strtoupper($this->input->post('shipingon'));
                    $save['details'] = $this->input->post('details');
                    if ($this->input->post('returnspolicy')) {
                        $save['returns_policy'] = 'YES';
                        $save['returns_days'] = $this->input->post('returnsdays');
                        $save['returns_note'] = $this->input->post('returnsnote');
                    } else {
                        $save['returns_policy'] = 'NO';
                        $save['returns_days'] = '';
                        $save['returns_note'] = '';
                    }
                    if ($this->input->post('special_product')) {
                        $save['days'] = $this->input->post('special_days');
                        $save['inv_num'] = $this->unique_id();
                        $save['user_id'] = $this->user_id;
                        $save['total'] = (int) $save['days'] * (double) get_option('special_product_price');
                        $save['must_pay'] = $save['total'];
                        $save['title'] = 'message_special_product';
                        $save['for'] = 'special_product';
                    }
                    $save['images'] = serialize($images);
                    if ($this->product->save($save, array('id' => $id), TRUE)) {
                        if ($this->input->post('special_product')) {
                            $this->load->model('invoicies_model');
                            $this->invoicies_model->save($save);
                        }
                        $this->load->model('categories_model', 'cats');
                        $cat = $this->cats->get(array('categories.id' => $this->input->post('subcat')), FALSE, 'row');
                        if ($cat->additional != '0') {
                            $additional = get_cat_additional($cat->id);
                            if ($additional) {
                                $addpost = $this->input->post('additional');
                                $adata['product_id'] = $id;
                                $adata['category_id'] = $this->input->post('subcat');
                                delete_product_additional($id);
                                foreach ($additional as $addt) {
                                    if (key_exists($addt->code, $addpost)) {
                                        if ($addt->type == 'checkbox')
                                            $adata['value'] = serialize($addpost[$addt->code]);
                                        else
                                            $adata['value'] = $addpost[$addt->code];
                                        $adata['code'] = $addt->code;
                                        save_product_additional($adata);
                                    }
                                }
                            }
                        }
                        $this->session->unset_userdata('post');
                        $this->themes->set_message(array('type' => 'success', 'url' => 'store', 'message' => 'message_save_success'));
                    } else {
                        get_save_error();
                    }
                } else {
                    get_validation_errors();
                }
            }
            $this->pass['trades'] = $this->trades->get();
            $this->pass['prodimg'] = $values['prodimg'];
            $this->pass['prodvedio'] = $values['prodvedio'];
            $this->pass['storeid'] = $store->id;
            $this->pass['product'] = $product;
            $this->session->unset_userdata('post');
            $this->themes->render('products/edit', $this->pass);
        } else {
            show_404();
        }
    }
    
    private function unique_id() {
        $this->load->model('invoicies_model');
        $string = strrev(md5(time() + $this->session->userdata('session_id')));
        $unique = substr($string, 0, 9);
        $temp = $this->invoicies_model->get(array('inv_num' => $unique));
        if (count($temp) > 0) {
            $this->unique_id();
        } else {
            return $unique;
        }
        return false;
    }

    function suggest() {
        
    }

    function subcats($id = false) {
        $return = '<option value="0" ';
        if (form_val('subcat') == '0')
            $return .= 'selected';
        $return .= ' >' . lang('label_select_subcat') . '</option>';
        if ($id) {
            $this->load->model('categories_model', 'cats');
            $temp = $this->cats->get(array('parent' => $id));
            if ($temp) {
                foreach ($temp as $t) {
                    $title = unserialize($t->title);
                    $title = (isset($title[LANG])) ? $title[LANG] : ((LANG == 'ar') ? $title['en'] : $title['ar']);
                    $return .= '<option value="' . $t->id . '" ';
                    if (form_val('subcat') == $t->id)
                        $return .= 'selected';
                    $return .= ' >' . $title . '</option>';
                }
            }
            die($return);
        } else {
            die($return);
        }
    }

    function needcolor($id = false) {
        if ($id) {
            $this->load->model('categories_model', 'cats');
            $temp = $this->cats->get(array('categories.id' => $id), $count = FALSE, $type = 'row');
            die(strtolower($temp->need_color));
        } else {
            die(false);
        }
    }

    function needsize($id = false) {
        if ($id) {
            $this->load->model('categories_model', 'cats');
            $temp = $this->cats->get(array('categories.id' => $id), $count = FALSE, $type = 'row');
            die(strtolower($temp->need_size));
        } else {
            die(false);
        }
    }

    function view($id = false) {
        if ($id) {
            $product = $this->product->is_found(array('id' => $id), array(), 'row', 'products');
            $this->pass['product'] = $product;
            $this->product->incrment(array('id' => $id));
            $this->themes->render('products/view', $this->pass);
        } else {
            show_404();
        }
    }

    function additionaldata($catid = false, $prodid = false) {
        if (is_numeric($catid)) {
            $this->load->model('categories_model', 'cats');
            $temp = $this->cats->get(array('categories.id' => $catid), FALSE, 'row');
            if ($temp) {
                if ($temp->additional != '0') {
                    if(is_numeric($prodid)){
                        $pro = $this->product->get(array('id' => $prodid), FALSE, 'row');
                        if($pro){
                            $pass['prodadditional'] = get_product_additional($prodid);
                        }
                    }
                    $pass['additional'] = get_cat_additional($catid);
                    die($this->load->view($this->themes->Cms_themes() . '/products/additionaldata', $pass, TRUE));
                }
            }
        }
        die();
    }

}
